<!--
 * @Description: 
 * @Author: Catherine
 * @Date: 2024-05-30 17:08:14
 * @LastEditor: Catherine
 * @LastEditTime: 2024-05-30 17:08:17
-->
<template>
  <Dropdown
    placement="bottom"
    :trigger="['click']"
    :dropMenuList="sysList"
    :selectedKeys="selectedKeys"
    @menu-event="handleMenuEvent($event, 1)"
    overlayClassName="app-locale-picker-overlay"
  >
    <span class="cursor-pointer flex items-center">
      <Icon icon="ion:check" />
      <span v-if="showText" class="ml-1">{{ getSystemText }}</span>
    </span>
  </Dropdown>
</template>
<script lang="ts" setup>
  import type { SystemType } from '#/config';
  import type { DropMenu } from '@/components/Dropdown';
  import { ref, watchEffect, unref, computed, onMounted } from 'vue';
  import { Dropdown } from '@/components/Dropdown';
  import Icon from '@/components/Icon/Icon.vue';
  import { systemList } from '@/settings/systemSetting';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import { useGo } from '@/hooks/web/usePage';
  import { PageEnum } from '@/enums/pageEnum';

  const go = useGo();
  const props = defineProps({
    /**
     * Whether to display text
     */
    showText: { type: Boolean, default: true },
    /**
     * Whether to refresh the interface when changing
     */
    reload: { type: Boolean },
  });

  const selectedKeys = ref<string[]>([]);

  const appStore = useAppStoreWithOut();
  const sysList = appStore.getSystemList;
  console.log(sysList, 'sysList');

  const getSystem = computed(() => appStore.getSystem);
  console.log('appStoregetSystem', getSystem);

  const getSystemText = computed(() => {
    const key = selectedKeys.value[0];
    if (!key) {
      return '';
    }
    console.log('sysList----------------', sysList);
    console.log('systemList----------------', systemList);

    return sysList.find((item) => item.name === key)?.text;
  });

  onMounted(() => {
    console.log('getSystem=====22222222222222222222222222============', appStore.getSystem);

    !appStore.getSystem && handleMenuEvent(sysList[0], 0);
  });

  watchEffect(() => {
    selectedKeys.value = [unref(getSystem)];
  });

  async function toggleSystem(system: SystemType | string, type: number) {
    selectedKeys.value = [system as string];
    console.log('设置端', system);

    appStore.setSystemInfo({ system });
    go(PageEnum.BASE_HOME);
    type === 1 &&
      setTimeout(() => {
        props.reload && location.reload();
      }, 300);
  }

  function handleMenuEvent(menu: DropMenu, type: number) {
    console.log('unref(getSystem)', unref(getSystem));

    if (!menu || unref(getSystem) === menu.name) {
      return;
    }
    console.log('menu**********************', menu.name);

    toggleSystem(menu.name as string, type);
  }
</script>

<style lang="less">
  .app-locale-picker-overlay {
    .ant-dropdown-menu-item {
      min-width: 160px;
    }
  }
</style>
